package com.common.android.ui.LocalAlbum;

import java.io.File;
import java.io.FileFilter;
import java.io.ObjectStreamClass;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.IntentService;
import android.content.Intent;
import android.os.Build.VERSION;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.text.TextUtils;

public class ImageSearchService extends IntentService {
	
	final String[] m_photoSuffixes = new String[] { ".png", ".jpg", ".gif", ".bmp",".jpeg" }; // 注意英文字母全部用小写

	public ImageSearchService() {
		super("FileSearch");	
	}

	private boolean isImage(String strFile){
		for (String suffix : m_photoSuffixes) {
			if (strFile.endsWith(suffix)) {
				return true;
			}
		}
		return false;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onHandleIntent(Intent intent) {
		LocalImageController.getInstance().clearLocalMedia();

		StorageManager sm = (StorageManager) getSystemService(STORAGE_SERVICE);
		try {
			if(Integer.parseInt(VERSION.SDK) >= 11){
                Class<?> cls = null;// = new Class<T>();
                Object obj = null;

				String[] volumePaths =  (String[]) sm.getClass().getMethod("getVolumePaths", cls).invoke(sm, obj);
				if(null != volumePaths){
					for(int i = volumePaths.length -1; i >=0 ; i--){
						 startTraversal(volumePaths[i]);
					}
				}else{
					String rootPath = Environment.getExternalStorageDirectory().getPath();
					startTraversal(rootPath);
				}
			}else{
				String rootPath = Environment.getExternalStorageDirectory().getPath();
				startTraversal(rootPath);
			}
			
			LocalImageController.getInstance().notifyObservers();			
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}
	
	//取得路径文件夹名
	public String getDirName(String strDir) {
		if (null == strDir) {
			return "";
		}

		// 移除末尾 '/'
		String strRet = new String(strDir);
		if (strRet.endsWith("/")) {
			strRet = strRet.substring(0, strRet.length());
		}

		int iPos = strRet.lastIndexOf('/');
		return strRet.substring(iPos + 1, strRet.length());
	}
	
	private void startTraversal(String path){
		if(TextUtils.isEmpty(path)){
			return;
		}
		traversal1(new String[]{path},0);
	}
	
	private void traversal1(final String[] directories, int traversalCount) {
		traversalCount++;
		for (String dirPath : directories) {
			File dir = new File(dirPath);
			if (!dir.isDirectory() || getDirName(dirPath).startsWith(".")) {
				continue;
			}

			FileInfo dirInfo = new FileInfo();
			dirInfo.mFilePathOrName = dir.getAbsolutePath();
			dirInfo.mLastModified = dir.lastModified();

			final SortedMediaFiles photo = new SortedMediaFiles();
			final SortedMediaFiles files = new SortedMediaFiles();
			photo.mDirInfo = dirInfo;
			files.mDirInfo = dirInfo;

			@SuppressWarnings("unused")
			File[] dirs = dir.listFiles(new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					if (pathname.isDirectory()) {
						String name = pathname.getName();
						FileInfo fi = new FileInfo();
						fi.mFilePathOrName = name;
						fi.mLastModified = pathname.lastModified();
						files.addFile(fi);
						return false;
					} else {
						String name = pathname.getName();
						String lcName = pathname.getName().toLowerCase(
								Locale.getDefault());

						boolean bIsImage = isImage(lcName);

						if (bIsImage) {
							FileInfo fi = new FileInfo();
							fi.mFilePathOrName = photo.mDirInfo.mFilePathOrName + "/" + name;
							fi.mLastModified = pathname.lastModified();
							// 更新最后更新时间
							photo.mDirInfo.mLastModified = Math.max(fi.mLastModified,
									photo.mDirInfo.mLastModified);

							photo.addFile(fi);
						}
					}
					return false;
				}
			});

			if (!photo.isFilesEmpty()) {
				LocalImageController.getInstance().addMediaFile(photo);
			}

			dir = null;
			dirs = null;
			List<FileInfo> listFI = files.getFilesList();
			if (null != listFI) {
				ArrayList<String> DCIMList = new ArrayList<String>();// 为了优先存放相册目录
				ArrayList<String> otherList = new ArrayList<String>();
				for (FileInfo fi : listFI) {
					if (fi.mFilePathOrName.startsWith(".")
							|| fi.mFilePathOrName.contains("face")
							|| fi.mFilePathOrName.contains("cover")
							|| fi.mFilePathOrName.contains("show")) {
						continue;
					}
					String path = files.mDirInfo.mFilePathOrName + "/"
							+ fi.mFilePathOrName;
					if (path.contains("DCIM")) {
						DCIMList.add(path);
					} else {
						otherList.add(files.mDirInfo.mFilePathOrName + "/"
								+ fi.mFilePathOrName);
					}
				}
				DCIMList.addAll(otherList);
				if (DCIMList.size() < 1) {
					continue;
				}
				
				if (traversalCount < 3) {
					String[] arrayDirs = new String[DCIMList.size()];
					traversal1(DCIMList.toArray(arrayDirs), traversalCount);
				}
				otherList.clear();
				DCIMList.clear();
				otherList = null;
				DCIMList = null;
			}
		}
	}
	
}
